package com.book.controller;

import com.book.model.entity.*;
import com.book.model.service.TmpCacheService;
import com.book.utils.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin
public class BaseController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    @Autowired
    protected TmpCacheService tmpCacheService;





    protected boolean saveToken(String tag, User user, int days){
        String token = null;
        try {
            token = MD5Util.MD5Encode(tag+"_"+user.getAccount()+"#@#"+user.getId()+"#@#"+System.currentTimeMillis());
            if(days == 0){
                days = 3600*1000*2;
            }else{
                days = 3600*1000*24*days;
            }
            tmpCacheService.set(token,""+user.getId(),days);
            user.setAccessToken(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    protected boolean removeToken(User user){
        try {
            if(user.getAccessToken() != null) {
                String uid = tmpCacheService.get(user.getAccessToken());
                if(uid != null){
                    tmpCacheService.delete(user.getAccessToken());
                }
                user.setAccessToken(null);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
